import { defineStore } from 'pinia'
import { ref } from 'vue'
import { 
  userLogin as loginApi, 
  userRegister as registerApi, 
  getCurrentUser, 
  updateUserProfile,
} from '@/api/user'
import { setUserToken, removeUserToken, getUserToken } from '@/utils/userAuth'

export const useUserStore = defineStore('user', () => {
  const userInfo = ref(null)
  const token = ref(getUserToken() || '')
  const isLoggedIn = ref(!!token.value)

  // 用户登录
  const userLogin = async (loginData) => {
    try {
      const response = await loginApi(loginData)
      // 根据后端返回的数据结构，token和userInfo在data对象中
      token.value = response.data.token
      userInfo.value = response.data.userInfo
      setUserToken(response.data.token)
      isLoggedIn.value = true
      return response
    } catch (error) {
      throw error
    }
  }
  
  // 用户注册
  const userRegister = async (registerData) => {
    try {
      const response = await registerApi(registerData)
      return response
    } catch (error) {
      throw error
    }
  }

  // 获取当前用户信息
  const fetchCurrentUserInfo = async () => {
    try {
      if (!token.value) {
        throw new Error('未登录')
      }
      const response = await getCurrentUser()
      userInfo.value = response.data
      return response
    } catch (error) {
      console.error('获取用户信息失败', error)
      throw error
    }
  }

  // 更新用户信息
  const updateUser = async (data) => {
    try {
      const response = await updateUserProfile(data)
      userInfo.value = { ...userInfo.value, ...response.data }
      return response
    } catch (error) {
      throw error
    }
  }
  // 用户退出登录
  const userLogout = () => {
    token.value = ''
    userInfo.value = null
    isLoggedIn.value = false
    removeUserToken()
  }

  return {
    userInfo,
    token,
    isLoggedIn,
    userLogin,
    userRegister,
    fetchCurrentUserInfo,
    updateUser,
    userLogout,
  }
}, {
  persist: true
})